const path = require('path')
const fs = require('fs-extra')
const { spawn } = require('child_process')

//#region 
function wsfb(wss, callback) {
    wss.on('connection', ws => {
        // console.log(`【${wss.options.port}】新的WebSocket连接`)
        // console.log(`\x1B[42m ${wss.options.port} \x1B[0m 新的WebSocket连接`)

        const send = data => ws.send(JSON.stringify({
            msg: data,
            code: 0
        }))

        const error = (data, code = 1) => ws.send(JSON.stringify({
            msg: data,
            code: code
        }))

        // 监听消息事件
        ws.on('message', message => callback(JSON.parse(message.toString()), send, error))

        // 监听关闭事件
        ws.on('close', () => console.log(`\x1B[47m ${wss.options.port} \x1B[0m WebSocket连接关闭`))
    })
}
//#endregion


const wsf = {
    // 菜单命令
    menu: wss => wsfb(wss, (msg, send, error) => {
        switch (msg.type) {
            case 'query':
                send({ a: 3, b: 5 })
                // setTimeout(() => wss.close(), 1000)
                break;

            default:
                break;
        }
    }),
    // 常规命令
    cmd: wss => wsfb(wss, (msg, send, error) => {
        switch (msg.type) {
            case 'url2base64':
                const process = spawn(path.join(__static, 'app_modules/url2base64/url2base64.exe'), [msg.url])
                process.stdout.on('data', e => {
                    send(e.toString())
                    // wss.close()
                })
                break;

            default:
                break;
        }
    })
}



module.exports =  { wsf, wsfb }